from django.http import JsonResponse
from django.shortcuts import redirect,render
from web import models
from utils.pager import Pagination
from web.forms.policy_form import *

def policy_list(request):
    queryset = models.PricePolicy.objects.all()
    pager = Pagination(request, queryset)
    pather_string = pager.html()
    return render(request,'policy_list.html',locals())

def policy_add(request):
    if request.method == "GET":
        form = PolicyAddForm()
        return render(request,'form.html',{'form':form})
    form = PolicyAddForm(request.POST)
    if not form.is_valid():
        return render(request,'form.html',{'form':form})
    form.save()
    return redirect('policy_list')
def policy_edit(request,pk):
    policy_obj = models.PricePolicy.objects.get(id=pk)
    if request.method == "GET":
        form = PolicyAddForm(instance=policy_obj)
        return render(request,'form.html',{'form':form})
    form = PolicyAddForm(request.POST,instance=policy_obj)
    if not form.is_valid():
        return render(request,'form.html',{'form':form})
    form.save()
    return redirect('policy_list')

def policy_delete(request):
    cid = request.GET.get('cid',0)
    if not cid:
        return JsonResponse({'status':False,'detail':'请选择删除数据'})
    policy_obj = models.PricePolicy.objects.filter(id=cid).first()
    if not policy_obj:
        return JsonResponse({'status':False,'detail':'删除数据不存在'})
    return JsonResponse({'status':True})
